#include <base\viewVolume.h>
#include <base\dprotation.h>

void 
viewVolume::perspective(float fovy, float aspect, float nearval, float farval) {
  this->dpvv.perspective(fovy, aspect, nearval, farval);
  this->dpvv.copyValues(*this);
}

void
viewVolume::translateCamera(const vec3f & v)
{
  vec3d dpv(v.x, v.y, v.z);
  dpvv.translateCamera(dpv);
  dpvv.copyValues(*this);
}

void
viewVolume::rotateCamera(const rotation & q)
{
  const float * quat = q.getValue();
  
  double dpquat[4];
  dpquat[0] = quat[0];
  dpquat[1] = quat[1];
  dpquat[2] = quat[2];
  dpquat[3] = quat[3];

  dprotation dpq(dpquat);
  dpvv.rotateCamera(dpq);
  dpvv.copyValues(*this);
}

void 
viewVolume::getViewVolumePlanes(plane planes[6]) const {
  this->dpvv.getViewVolumePlanes(planes);
}

bool 
viewVolume::intersect(const box3f & box) const {
  int i, j;
  vec3f bmin, bmax;
  bmin = box.getMin();
  bmax = box.getMax();
  vec3f pts[8];

  // create the 8 box corner points
  for (i = 0; i < 8; i++) {
    pts[i][0] = i & 1 ? bmin[0] : bmax[0];
    pts[i][1] = i & 2 ? bmin[1] : bmax[1];
    pts[i][2] = i & 4 ? bmin[2] : bmax[2];
  }

  plane planes[6];
  getViewVolumePlanes(planes);

  for (i = 0; i < 6; i++) {
    for (j = 0; j < 8; j++) {
      if (planes[i].isInHalfSpace(pts[j])) break;
    }
    if (j == 8) return false;
  }
  return true;
}
